package com.shiku.mianshi.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.support.jedis.JedisTemplate;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.PayConstants;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.example.UserExample;
import cn.xyz.mianshi.example.UserQueryExample;
import cn.xyz.mianshi.example.UserUpdateExample;
import cn.xyz.mianshi.service.impl.ConsumeRecordManagerImpl;
import cn.xyz.mianshi.service.impl.UserManagerImpl;
import cn.xyz.mianshi.utils.KSessionUtil;
import cn.xyz.mianshi.vo.ConsumeRecord;
import cn.xyz.mianshi.vo.PageVO;
import cn.xyz.mianshi.vo.User;
import cn.xyz.mianshi.vo.UserStatusCount;
import cn.xyz.service.KXMPPServiceImpl;
import cn.xyz.service.KXMPPServiceImpl.MessageBean;

import com.alibaba.fastjson.JSON;
import com.alipay.util.AliPayUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mongodb.BasicDBObject;
import com.mongodb.Cursor;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.wxpay.utils.WXPayUtil;
import com.wxpay.utils.WxPayDto;

/**
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/user")
public class UserController extends AbstractController {

	@Resource(name = "jedisTemplate")
	protected JedisTemplate jedisTemplate;
	@Autowired
	private UserManagerImpl userManager;
	@Autowired
	ConsumeRecordManagerImpl consumeRecordManager;
	@Resource(name = "dsForRW")
	private Datastore dsForRW;
	@Resource(name = "dsForTigase")
	private Datastore dsForTigase;

	@RequestMapping(value = "/register")
	public JSONMessage register(@Valid UserExample example) {
		example.setPhone(example.getTelephone());
		example.setTelephone(example.getAreaCode() + example.getTelephone());
		Object data = userManager.registerIMUser(example);
		return JSONMessage.success(null, data);
	}

	// 验证码密码都可以登陆
	@RequestMapping(value = "/login")
	public JSONMessage login(@ModelAttribute UserExample example) {
		Object data = userManager.loginv1(example);
		return JSONMessage.success(null, data);
	}

	@RequestMapping(value = "/getUsersByPhone")
	public JSONMessage getUsersByPhone(
			@RequestParam(defaultValue = "") String telephone) {
		Object data = userManager.getUsersByPhone(telephone);
		return JSONMessage.success(null, data);
	}

	/*
	 * @RequestMapping(value = "/login/v1") public JSONMessage
	 * loginv1(@ModelAttribute UserExample example) {
	 * //example.setTelephone(example.getAreaCode()+example.getTelephone());
	 * Object data = userManager.login(example); return
	 * JSONMessage.success(null, data); }
	 */

	@RequestMapping(value = "/login/auto")
	public JSONMessage loginAuto(@RequestParam String access_token,
			@RequestParam int userId, @RequestParam String serial,
			@RequestParam(defaultValue = "") String appId) {
		Object data = userManager
				.loginAuto(access_token, userId, serial, appId);
		return JSONMessage.success(null, data);
	}

	@RequestMapping(value = "/logout")
	public JSONMessage logout(@RequestParam String access_token,
			@RequestParam(defaultValue = "86") String areaCode, String telephone) {
		userManager.logout(access_token, areaCode, telephone);
		return JSONMessage.success(null);
	}

	@RequestMapping(value = "/outtime")
	public JSONMessage outtime(@RequestParam String access_token,
			@RequestParam int userId) {
		userManager.outtime(access_token, userId);
		return JSONMessage.success(null);
	}

	@RequestMapping("/update")
	public JSONMessage updateUser(@ModelAttribute UserExample param) {
		User data = userManager.updateUser(ReqUtil.getUserId(), param);
		return JSONMessage.success(null, data);
	}

	@RequestMapping("/channelId/set")
	public JSONMessage setChannelId(@RequestParam String deviceId,
			String channelId) {
		if (StringUtil.isEmpty(channelId))
			return JSONMessage.success();
		String key1 = String.format("user:%s:channelId", ReqUtil.getUserId());
		String key2 = String.format("user:%s:deviceId", ReqUtil.getUserId());
		String key3 = String.format("channelId:%s", channelId);
		jedisTemplate.del(key1, key2, key3);
		jedisTemplate.set(key1, channelId);
		jedisTemplate.set(key2, deviceId);
		jedisTemplate.set(key3, ReqUtil.getUserId() + "");

		return JSONMessage.success();
	}

	@RequestMapping(value = "/get")
	public JSONMessage getUser(@RequestParam(defaultValue = "0") int userId) {
		int loginedUserId = ReqUtil.getUserId();
		int toUserId = 0 == userId ? loginedUserId : userId;
		Object data = userManager.getUser(loginedUserId, toUserId);
		return JSONMessage.success(null, data);
	}

	// 此接口用于根据studentId,teacherId 查找学生数据
	@RequestMapping(value = "/get2")
	public JSONMessage getUser2(@RequestParam int studentId,
			@RequestParam int teacherId) {
		Object data = userManager.getUserByStuIdAndTeacId(studentId, teacherId);
		return JSONMessage.success(null, data);
	}

	@RequestMapping(value = "/query")
	public JSONMessage queryUser(@ModelAttribute UserQueryExample param) {
		Object data = userManager.query(param);
		return JSONMessage.success(null, data);
	}

	@RequestMapping("/password/reset")
	public JSONMessage resetPassword(
			@RequestParam(defaultValue = "86") String areaCode,
			@RequestParam(defaultValue = "") String telephone,
			@RequestParam(defaultValue = "") String randcode,
			@RequestParam(defaultValue = "") String newPassword) {
		JSONMessage jMessage;
		telephone = areaCode + telephone;
		if (StringUtil.isEmpty(telephone) || (StringUtil.isEmpty(randcode))
				|| StringUtil.isEmpty(newPassword)) {
			jMessage = KConstants.Result.ParamsAuthFail;
		} else {
			userManager.resetPassword(telephone, newPassword);
			Integer userId = ReqUtil.getUserId();
			KSessionUtil.deleteUserByUserId(userId);
			jMessage = JSONMessage.success(null);
		}

		return jMessage;
	}

	@RequestMapping("/password/update")
	public JSONMessage updatePassword(
			@RequestParam("oldPassword") String oldPassword,
			@RequestParam("newPassword") String newPassword) {
		JSONMessage jMessage;

		if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
			jMessage = KConstants.Result.ParamsAuthFail;
		} else {
			Integer userId = ReqUtil.getUserId();
			userManager.updatePassword(userId, oldPassword, newPassword);
			KSessionUtil.deleteUserByUserId(userId);
			jMessage = JSONMessage.success(null);
		}
		return jMessage;
	}

	@RequestMapping(value = "/settings")
	public JSONMessage getSettings(@RequestParam int userId) {
		Object data = userManager.getSettings(0 == userId ? ReqUtil.getUserId()
				: userId);
		return JSONMessage.success(null, data);
	}

	@RequestMapping(value = "/settings/update")
	public JSONMessage updateSettings(
			@ModelAttribute User.UserSettings userSettings) {
		Integer userId = ReqUtil.getUserId();
		Object data = userManager.updateSettings(userId, userSettings);
		KSessionUtil.deleteUserByUserId(userId);
		return JSONMessage.success(null, data);
	}

	@RequestMapping(value = "/recharge/getSign")
	public JSONMessage getSign(@RequestParam int payType,
			@RequestParam String price) {
		Map<String, String> map = Maps.newLinkedHashMap();
		String orderInfo = "";
		if (0 < payType) {
			String orderNo = AliPayUtil.getOutTradeNo();
			ConsumeRecord entity = new ConsumeRecord();
			entity.setUserId(ReqUtil.getUserId());
			entity.setTime(DateUtil.currentTimeSeconds());
			entity.setType(KConstants.MOENY_ADD);
			entity.setDesc("余额充值");
			entity.setStatus(KConstants.OrderStatus.CREATE);
			entity.setTradeNo(orderNo);
			entity.setPayType(payType);
			entity.setMoney(new Double(price));
			if (KConstants.PayType.ALIPAY == payType) {

				orderInfo = AliPayUtil.getOrderInfo("聘吧余额充值", "余额充值", price,
						orderNo);
				String sign = AliPayUtil.sign(orderInfo);
				consumeRecordManager.saveConsumeRecord(entity);
				map.put("sign", sign);
				map.put("orderInfo", orderInfo);
				System.out.println("orderInfo>>>>>" + orderInfo);
				// System.out.println("sign>>>>>"+sign);
				return JSONMessage.success(null, map);
			} else {
				WxPayDto tpWxPay = new WxPayDto();
				// tpWxPay.setOpenId(openId);
				tpWxPay.setBody("聘吧余额充值");
				tpWxPay.setOrderId(orderNo);
				tpWxPay.setSpbillCreateIp(PayConstants.WXSPBILL_CREATE_IP);
				tpWxPay.setTotalFee(price);
				consumeRecordManager.saveConsumeRecord(entity);
				Object data = WXPayUtil.getPackage(tpWxPay);
				return JSONMessage.success(null, data);
			}
		}
		return JSONMessage.failure("没有选择支付类型");
	}

	// @RequestMapping(value = "/useralladd")
	public JSONMessage useralladd() throws Exception {
		Cursor attach = dsForRW.getDB().getCollection("user").find();
		while (attach.hasNext()) {
			DBObject fileobj = attach.next();
			DBObject ref = new BasicDBObject();
			ref.put("user_id", fileobj.get("_id") + "@www.shiku.co");
			DBObject obj = dsForTigase.getDB().getCollection("tig_users")
					.findOne(ref);
			if (null != obj) {
				System.out.println("123");
			} else {
				KXMPPServiceImpl.getInstance().register(
						fileobj.get("_id").toString(),
						fileobj.get("password").toString());
			}
		}
		return JSONMessage.success();
	}

	@RequestMapping(value = "/Recharge")
	public JSONMessage Recharge(Double money, int type) throws Exception {
		String tradeNo = AliPayUtil.getOutTradeNo();
		Integer userId = ReqUtil.getUserId();
		Map<String, Object> data = Maps.newHashMap();
		// 创建充值记录
		ConsumeRecord record = new ConsumeRecord();
		record.setUserId(userId);
		record.setTradeNo(tradeNo);
		record.setMoney(money);
		record.setStatus(KConstants.OrderStatus.END);
		record.setType(KConstants.MOENY_ADD);
		record.setPayType(type);
		record.setDesc("余额充值");
		record.setTime(DateUtil.currentTimeSeconds());
		consumeRecordManager.save(record);
		try {
			Double balance = userManager.rechargeUserMoeny(userId, money,
					KConstants.MOENY_ADD);
			data.put("balance", balance);
			return JSONMessage.success(null, data);
		} catch (Exception e) {
			return JSONMessage.error(e);
		}

	}

	@RequestMapping(value = "/getUserMoeny")
	public JSONMessage getUserMoeny() throws Exception {
		Integer userId = ReqUtil.getUserId();
		Map<String, Object> data = Maps.newHashMap();
		Double balance = userManager.getUserMoeny(userId);
		if (null == balance)
			balance = 0.0;
		data.put("balance", balance);
		return JSONMessage.success(null, data);

	}

	@RequestMapping(value = "/getUserStatusCount")
	public JSONMessage getUserStatusCount(
			@RequestParam(defaultValue = "0") int pageIndex,
			@RequestParam(defaultValue = "100") int pageSize, String sign,
			String startDate, String endDate,
			@RequestParam(defaultValue = "0") int type) throws Exception {
		Map data = Maps.newHashMap();
		Map<String, Long> timeM = new HashMap<String, Long>();
		Query<UserStatusCount> query = dsForRW
				.createQuery(UserStatusCount.class);
		long currentTime = DateUtil.currentTimeSeconds();
		long startTime = 0;
		long endTime = 0;
		if (!StringUtils.isEmpty(sign)) {
			timeM = getTimes(new Integer(sign));
			startTime = timeM.get("startTime");
			endTime = timeM.get("endTime");

		} else {
			try {
				startTime = DateUtil.getDate(startDate, "yyyy-MM-dd").getTime() / 1000;
				endTime = DateUtil.getDate(endDate, "yyyy-MM-dd").getTime() / 1000;
			} catch (ParseException e) {
				e.printStackTrace();
				throw new RuntimeException("时间转换异常");
			}
		}

		if (0 < type)
			query.field("type").equal(type);
		if (0 != endTime) {
			query.field("time").greaterThanOrEq(startTime);
			query.field("time").lessThanOrEq(endTime);
		}
		query.order("time");

		List<UserStatusCount> list = query.asList();

		return JSONMessage.success(null, list);

	}

	@RequestMapping(value = "/getOnlinestateByUserId")
	public JSONMessage getOnlinestateByUserId(Integer userId) {
		Object data = userManager.getOnlinestateByUserId(userId);
		return JSONMessage.success(null, data);
	}

	/**
	 * 更新用户信息 
	 * @param example
	 * @return
	 */
	@RequestMapping(value ="/update2",method={ RequestMethod.POST})
	public JSONMessage update2(@Valid UserUpdateExample example) {
		//用户类型:1=学生、2=教师
		if(example.getUserType() == 1){
			if (example.getStudentId() == null) {
				JSONMessage.failure("studentId is null");
			}
			User user = userManager.getUserByStudentIdOrTeacherId(example.getStudentId(),null);
			if (user == null) {
				JSONMessage.failure("student info is null");
			}
			UserExample userExample = new UserExample();
			userExample.setClassname(example.getClassname());
			userExample.setGradeName(example.getGradeName());
			userExample.setNickname(example.getNickname());
			if(!StringUtil.isEmpty(example.getMobile())){
				userExample.setPhone(example.getMobile());
				userExample.setTelephone(userExample.getAreaCode()+example.getMobile());
			}
			userExample.setSex(example.getSex());
			userManager.updateUser(user.getUserId(), userExample);
			//KSessionUtil.deleteUserByUserId(user.getUserId());
			return JSONMessage.success(null);
			
		}else if(example.getUserType() == 2){
			if (example.getTeacherId() == null) {
				JSONMessage.failure("teacherId is null");
			}
			User user = userManager.getUserByStudentIdOrTeacherId(null,example.getTeacherId());
			if (user == null) {
				JSONMessage.failure("teacher info is null");
			}
			UserExample userExample = new UserExample();
			userExample.setNickname(example.getNickname());
			if(!StringUtil.isEmpty(example.getMobile())){
				userExample.setPhone(example.getMobile());
				userExample.setTelephone(userExample.getAreaCode()+example.getMobile());
			}
			userExample.setSex(example.getSex());
			userManager.updateUser(user.getUserId(), userExample);
			//KSessionUtil.deleteUserByUserId(user.getUserId());
			return JSONMessage.success(null);
			
		}
		return JSONMessage.failure("userType is error");
	}
	
	/**
	 * 推送消息
	 * @param studentId
	 * @param teacherId
	 * @param userId
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "/push" ,method={ RequestMethod.POST})
	public JSONMessage push(@RequestParam int fromUserId,@RequestParam String fromUserName,
			@RequestParam(required =false) int studentId,@RequestParam(required =false) int teacherId,@RequestParam(required =false) int userId,@RequestParam String content) {
//		try {
//			content = new String(content.getBytes("ISO-8859-1"), "utf-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//			return JSONMessage.failure("系统错误，请稍后再试");
//		}
		MessageBean mb = new MessageBean();
		mb.setContent(content);
		mb.setFromUserId(Integer.toString(fromUserId));
		mb.setFromUserName(fromUserName);
		mb.setType(1);
		mb.setTimeSend(DateUtil.currentTimeSeconds());
		try {
			if (studentId > 0 || teacherId > 0) {
				User user = userManager.getUserByStudentIdOrTeacherId(studentId,teacherId);
				if (user != null) {
					KXMPPServiceImpl.getInstance().send(user.getUserId(), JSON.toJSONString(mb));
				}
			}

			if (userId > 0) {
				KXMPPServiceImpl.getInstance().send(userId, JSON.toJSONString(mb));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JSONMessage.failure("系统错误，请稍后再试");
		}
		return JSONMessage.success(null);
//		try {
//			response.setContentType("text/html; charset=UTF-8");
//			PrintWriter writer = response.getWriter();
//			writer.write(
//					"<script type='text/javascript'>alert('\u6279\u91CF\u53D1\u9001\u6D88\u606F\u5DF2\u5B8C\u6210\uFF01');window.location.href='/pages/qf.jsp';</script>");
//			writer.flush();
//			writer.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
	
	/**
	 * 获取开始时间和结束时间
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Long> getTimes(Integer sign) {
		Long startTime = null;
		Long endTime = DateUtil.currentTimeSeconds();
		Map<String, Long> map = Maps.newLinkedHashMap();

		if (sign == -3) {// 最近一个月
			startTime = endTime - (KConstants.Expire.DAY1 * 30);
		} else if (sign == -2) {// 最近7天
			startTime = endTime - (KConstants.Expire.DAY1 * 7);
		} else if (sign == -1) {// 最近48小时
			startTime = endTime - (KConstants.Expire.DAY1 * 2);
		}
		// 表示今天
		else if (sign == 0) {
			startTime = DateUtil.getTodayMorning().getTime() / 1000;
		}

		else if (sign == 3) {
			startTime = DateUtil.strYYMMDDToDate("2000-01-01").getTime() / 1000;
		}

		map.put("startTime", startTime);
		map.put("endTime", endTime);
		return map;
	}
}
